package com.dhc.service.utils.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.dhc.service.entity.AdminLogin;

import java.util.Calendar;

public class JwtUtils {
	// 生成Token
	public static String getToken(AdminLogin adminLogin) {
		String token = "";
		Algorithm algorithm = Algorithm.HMAC256("secret");
		//long expire = 7 * 24 * 60 * 60 * 1000; // 7天后过期
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, 10);  // 10分钟后过期
		token = JWT.create()
				.withIssuer("dhc")
				.withClaim("userId", adminLogin.getAdminId())
				.withAudience(adminLogin.getAdminUsername())
				.withSubject(adminLogin.getAdminUsername())
				.withExpiresAt(calendar.getTime())
				.sign(algorithm);
		return token;
	}

	// 验证 token
	public static boolean checkToken(String token) {
		JWTVerifier jwtVerifier = JWT.require(
				Algorithm.HMAC256("secret")
		).build();

		try {
			jwtVerifier.verify(token);
			return true;
		} catch (JWTVerificationException e) {
			throw new RuntimeException("401 登录过期，请重新登录");
		}
	}

	public static String getIdByToken(String token) {
		return JWT.decode(token).getClaim("userId").asString();
	}
}


